<template>
	<view class="marquee-container">
		<!-- 滚动字幕内容 -->
		<view class="marquee-content" :style="{ transform: `translateX(${offset}px)` }">
			{{ text }}{{ text }}
		</view>
		<!-- 控制按钮 -->
		<view class="controls">
			<button @click="startScroll" :disabled="isPlaying">▶️ 开始</button>
			<button @click="stopScroll" :disabled="!isPlaying">⏹️ 停止</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				text: '这是一段在多端滚动显示的字幕内容，可以根据需要修改。',
				offset: 0,
				containerWidth: 0,
				textWidth: 0,
				animationTimer: null,
				isPlaying: false,
				speed: 2,
				platform: ''
			};
		},
		mounted() {
			this.initPlatform();
			this.initWidth();
		},
		methods: {
			// 初始化运行平台
			initPlatform() {
				// #ifdef H5
				this.platform = 'h5';
				// #endif
				// #ifdef MP-WEIXIN
				this.platform = 'wechat';
				// #endif
			},
			// 初始化容器和文本宽度
			initWidth() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.marquee-container').boundingClientRect((res) => {
					this.containerWidth = res.width;
				}).exec();
				query.select('.marquee-content').boundingClientRect((res) => {
					this.textWidth = res.width;
				}).exec();
			},
			// 启动滚动
			startScroll() {
				if (!this.isPlaying) {
					this.isPlaying = true;
					const animate = () => {
						this.offset -= this.speed;
						if (this.offset <= -this.textWidth) {
							this.offset = 0;
						}
						if (this.platform === 'h5') {
							this.animationTimer = requestAnimationFrame(animate);
						} else if (this.platform === 'wechat') {
							this.animationTimer = setTimeout(animate, 1000 / 60);
						}
					};
					if (this.platform === 'h5') {
						this.animationTimer = requestAnimationFrame(animate);
					} else if (this.platform === 'wechat') {
						this.animationTimer = setTimeout(animate, 1000 / 60);
					}
				}
			},
			// 停止滚动
			stopScroll() {
				this.isPlaying = false;
				if (this.platform === 'h5') {
					cancelAnimationFrame(this.animationTimer);
				} else if (this.platform === 'wechat') {
					clearTimeout(this.animationTimer);
				}
			}
		},
		beforeDestroy() {
			this.stopScroll();
		}
	};
</script>

<style scoped>
	/* 让滚动容器占据整个屏幕 */
	.marquee-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		overflow: hidden;
		background-color: #f0f0f0;
	}

	.marquee-content {
		white-space: nowrap;
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		will-change: transform;
		transition-timing-function: linear;
	}

	.controls {
		position: absolute;
		right: 10px;
		top: 50px;
		display: flex;
		gap: 10px;
	}

	button {
		padding: 8px 12px;
		border: none;
		border-radius: 4px;
		background-color: #007aff;
		color: white;
		font-size: 14px;
		cursor: pointer;
	}

	button:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}
</style>